import { ModernBaseService } from './ModernBaseService';

/**
 * 遗留Service适配器
 * 为老的静态Service类提供向新架构迁移的桥梁
 * 保持向后兼容性，同时逐步引入新的架构模式
 */
export class LegacyServiceAdapter {
    private static instances = new Map<string, any>();

    /**
     * 获取Service实例（单例模式）
     * @param ServiceClass Service类
     * @param container DI容器（可选）
     * @returns Service实例
     */
    static getInstance<T extends ModernBaseService>(
        ServiceClass: new (container?: any) => T,
        container?: any
    ): T {
        const className = ServiceClass.name;
        
        if (!this.instances.has(className)) {
            const instance = new ServiceClass(container);
            this.instances.set(className, instance);
            
            // 自动初始化
            instance.init().catch(error => {
                console.error(`Failed to initialize service ${className}:`, error);
            });
        }

        return this.instances.get(className);
    }

    /**
     * 注册Service实例
     * @param name Service名称
     * @param instance Service实例
     */
    static registerInstance<T>(name: string, instance: T): void {
        this.instances.set(name, instance);
    }

    /**
     * 清理所有Service实例
     */
    static async cleanup(): Promise<void> {
        const cleanupPromises: Promise<void>[] = [];

        for (const [name, instance] of this.instances) {
            if (instance && typeof instance.destroy === 'function') {
                cleanupPromises.push(
                    instance.destroy().catch((error: any) => {
                        console.error(`Failed to cleanup service ${name}:`, error);
                    })
                );
            }
        }

        await Promise.all(cleanupPromises);
        this.instances.clear();
        console.log('All legacy services cleaned up');
    }

    /**
     * 获取所有已注册的Service名称
     */
    static getRegisteredServices(): string[] {
        return Array.from(this.instances.keys());
    }

    /**
     * 检查Service是否已注册
     * @param name Service名称
     * @returns 是否已注册
     */
    static hasService(name: string): boolean {
        return this.instances.has(name);
    }

    /**
     * 移除Service实例
     * @param name Service名称
     */
    static async removeService(name: string): Promise<void> {
        const instance = this.instances.get(name);
        if (instance && typeof instance.destroy === 'function') {
            await instance.destroy();
        }
        this.instances.delete(name);
    }
}

/**
 * 静态方法到实例方法的适配器装饰器
 * 用于渐进式迁移静态Service类
 */
export function staticToInstance<T extends ModernBaseService>(
    ServiceClass: new (container?: any) => T
) {
    return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        const originalMethod = descriptor.value;

        descriptor.value = function(...args: any[]) {
            // 获取Service实例
            const instance = LegacyServiceAdapter.getInstance(ServiceClass);
            
            // 调用实例方法
            if (typeof (instance as any)[propertyKey] === 'function') {
                return (instance as any)[propertyKey](...args);
            } else {
                // 如果实例没有对应方法，回退到原始静态方法
                return originalMethod.apply(target, args);
            }
        };

        return descriptor;
    };
}

/**
 * 异步静态方法适配器
 */
export function asyncStaticToInstance<T extends ModernBaseService>(
    ServiceClass: new (container?: any) => T
) {
    return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
        const originalMethod = descriptor.value;

        descriptor.value = async function(...args: any[]) {
            try {
                // 获取Service实例
                const instance = LegacyServiceAdapter.getInstance(ServiceClass);
                
                // 确保Service已初始化
                if (!instance.isReady()) {
                    await instance.init();
                }
                
                // 调用实例方法
                if (typeof (instance as any)[propertyKey] === 'function') {
                    return await (instance as any)[propertyKey](...args);
                } else {
                    // 如果实例没有对应方法，回退到原始静态方法
                    return await originalMethod.apply(target, args);
                }
            } catch (error) {
                console.error(`Error in adapted method ${propertyKey}:`, error);
                throw error;
            }
        };

        return descriptor;
    };
}

/**
 * 创建静态Service到现代Service的代理
 * @param LegacyClass 原始静态Service类
 * @param ModernClass 新的现代Service类
 * @returns 代理对象
 */
export function createServiceProxy<T extends ModernBaseService>(
    LegacyClass: any,
    ModernClass: new (container?: any) => T
): any {
    const instance = LegacyServiceAdapter.getInstance(ModernClass);

    return new Proxy(LegacyClass, {
        get(target, prop, receiver) {
            // 如果现代实例有这个方法，优先使用
            if (instance && typeof instance[prop as keyof T] === 'function') {
                return (instance[prop as keyof T] as any).bind(instance);
            }
            
            // 回退到原始静态方法
            const originalValue = Reflect.get(target, prop, receiver);
            if (typeof originalValue === 'function') {
                return originalValue.bind(target);
            }
            
            return originalValue;
        },

        set(target, prop, value, receiver) {
            // 设置操作同时更新原始类和实例
            if (instance && prop in instance) {
                (instance as any)[prop] = value;
            }
            return Reflect.set(target, prop, value, receiver);
        }
    });
}
